(function (){
	var Model = function (canvas){
		var me = this;
		me.canvas = canvas;
		me.ctx = canvas.getContext('2d');
		me.number = 100;
		me.particles = [];
		me.genParticle();
		var x= me.init()
		const {particles} = me;
		setInterval(function(){me.draw(particles)},17);
		
	}
	
	window.Particle = Model;
	
	//定义一个成员函数，生成粒子
	Model.prototype.genParticle = function (){
		var me = this;
		return {
			x:Math.floor(Math.random() * me.canvas.width),
			y:Math.floor(Math.random() * me.canvas.height),

			
			//粒子速度和方向		
			direction :2 * Math.PI * Math.random(),
			speed : Math.random() * 20,
			
			//大小，颜色
			radius : Math.round(Math.random()*10),
			r:Math.floor(Math.random()*255),
			g:Math.floor(Math.random()*255),
			b:Math.floor(Math.random()*255),
			a:Math.floor(Math.random()*255),
			
		}

		
	}
	
	//在canvas上绘制粒子
	Model.prototype.draw = function (particle){
		var me = this;
		const {ctx} = me;
		ctx.clearRect(0,0,me.canvas.width,me.canvas.height)
		for(item of me.particles)
		{
			const {x, y, speed, direction, radius,r,g,b,a,particles} = item;
			ctx.beginPath();
			ctx.fillStyle = 'rgba('+[r,g,b,a]+')'
			ctx.arc(x,y,radius,0,2*Math.PI);
			ctx.stroke();
			ctx.fill();
			ctx.closePath()
			item.vector = {
			x:speed * Math.cos(direction),     //粒子在x轴的速度
			y:speed * Math.sin(direction)        //粒子在y轴的速度
			};
		}
		me.run();
		
	}
	
	
	
	
	//初始化100个粒子
	Model.prototype.init = function (){
		var me = this;
		const {number,particles,genParticle,draw} = me;
		if(particles.length === 0)
		{
			for (var i=0; i<number; i++)
			{
				particles[i] = me.genParticle();
			}
		}
		else{
			particles.push(me.genParticle())
		}
		
		
	}
	Model.prototype.run = function() {
		var me = this;
		const {number,particles,genParticle,draw} = me;
		
		for(var i = 0;i <number; i++)
		{
			me.particles[i].x += particles[i].vector.x;
			me.particles[i].y += particles[i].vector.y;
			if(me.particles[i].x >  me.canvas.width || me.particles[i].y > me.canvas.height||me.particles[i].x < 0 || me.particles[i].y < 0)
			{
				me.particles.splice(i, 1);
				me.init();
			}
		}
	}
}
())